package com.javatip.project.queue.repository;

import com.javatip.project.queue.domain.Task;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Optional;

public interface QueueRepository extends JpaRepository<Task, Integer> {
    List<Task> findAllByOrderByInTimeAsc();

    @Modifying
    @Transactional
    @Query("DELETE FROM Task q WHERE q.taskType = :taskType AND q.taskID = :taskID")
    int deleteByTaskTypeAndTaskID(String taskType, int taskID);

    Optional<Task> findFirstByOrderByInTimeAsc();


    @Query(value = "SELECT * FROM task_queue WHERE taskID = :taskID and taskType=:type", nativeQuery = true)
    Optional<Task> findByTaskID(@Param("taskID") Integer taskID,@Param("type") String type);

    @Query(value = "SELECT COUNT(*) + 1 FROM task_queue WHERE inTime < (SELECT inTime FROM task_queue WHERE taskId = :taskID and taskType=:type)", nativeQuery = true)
    int getTimePositionByTaskID(@Param("taskID") Integer taskID,@Param("type") String type);


}